<?php

namespace app\api\model;

use think\Model;

/**
 * SpecialActivity
 */
class Activity extends Model
{
    // 表名
    protected $name = 'special_activity';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 追加属性
    protected $append = [
        'tags',
    ];

    protected static function onAfterInsert($model): void
    {
        if (is_null($model->weigh)) {
            $pk = $model->getPk();
            if (strlen($model[$pk]) >= 19) {
                $model->where($pk, $model[$pk])->update(['weigh' => $model->count()]);
            } else {
                $model->where($pk, $model[$pk])->update(['weigh' => $model[$pk]]);
            }
        }
    }
    public function getImageAttr($value): string
    {
        return $value?full_url($value): '';
    }
    public function getTagsAttr($value, $row): array
    {
        $tags = \app\api\model\SpecialTags::whereIn('id', $row['special_tags_ids'])->field('tag_name,bgcolor')->select()->toArray();
        return  $tags?:[];
    }

    public function getTagsIdsAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setTagsIdsAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function getContentAttr($value): string
    {
        return !$value ? '' : htmlspecialchars_decode($value);
    }

    public function Cate(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\api\model\Category::class, 'cate_id', 'id');
    }
}